#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

#include "ipc_api.h" 

typedef struct {
	int running;
}lockClient_s;

static lockClient_s lockClient = {1};
static lockClient_s *pLockClient = &lockClient;

static void signalRountine(int signNo)
{
	switch(signNo)
	{
		case SIGINT://ctrl+c
			pLockClient->running = 0;
			ipcLogDebug("recv SIGINT ,exit \n");
			break;
		case SIGTERM://kill
			pLockClient->running = 0;
			ipcLogDebug("recv SIGTERM ,exit \n");
			break;
	}
}

int main(int argc,char* argv[])
{
	ipcRet_e ret = ipcSuccess;
	ipcLog_s log = {IPC_LOG_DEBUG,IPC_LOG_2_STDERR};	
	int create	 = FALSE;

	signal(SIGINT,signalRountine);
	signal(SIGTERM,signalRountine);

	ret = ipcLogInit(&log);
	ipcLogCheckRetThenReturn(ret);

	ipcShareMemoryInit(create);
	ipcLogCheckRetThenReturn(ret);
	
	ret = ipcLockInit(create);
	ipcLogCheckRetThenReturn(ret);

	while(pLockClient->running)
	{	
		int sleepTime = random()%SLEEP_TIME_RANDOM_MOD;
		ipcLockContext_s context ={getpid(),(char*)"client"};
		
		ipcLogDebug("pid %d sleepTimeUs %d \n",getpid(),sleepTime);
		
		ret = ipcLock(&context);
		if(ipcSuccess == ret)
		{
			ipcUnlock(&context);
		}

		sleep(sleepTime);
	}
	
	ipcLockDeinit(create);
	ipcShareMemoryDeinit(create);
	ipcLogDeinit();
	
	return 0;
}
